package com.czk.netty.netty.simple;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

/**
 * @Author:ChenZhangKun
 * @Date: 2021/1/13 23:00
 */
public class NettyClient {
    public static void main(String[] args) {
        EventLoopGroup eventExecutors = null;
        try {
            // 客户端的一个事件循环组
            eventExecutors = new NioEventLoopGroup();
            // 创建客户端启动对象
            Bootstrap bootstrap = new Bootstrap();
            // 设置相关参数
            bootstrap
                    // 设置线程组
                    .group(eventExecutors)
                    // 通道的实现类
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            // 加入自己的处理器
                            socketChannel.pipeline().addLast(new NettyClientHandler());
                        }
                    });
            System.out.println("客户端准备好、、、");
            // 启动客户端连接诶服务器端 设计netty的异步模型
            ChannelFuture sync = bootstrap.connect("127.0.0.1", 7000).sync();
            sync.channel().closeFuture().sync();
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            if (eventExecutors != null) {
                eventExecutors.shutdownGracefully();
            }
        }

    }
}
